package org.shellex.javame.utility;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;
 
/**
 * @author Favo
 * Preferences - Java - Code Style - Code Templates
 */
public class ProgressGaugeUI implements ProgressObserver, CommandListener {
 
    private static final int GAUGE_MAX = 8;
 
    private static final int GAUGE_LEVELS = 4;
 
    private static ProgressGaugeUI pgUI;
 
    private Form f;
 
    private Gauge gauge;
 
    private Command stopCMD;
 
    boolean stopped;
 
    boolean stoppable;
   
    int current;
 
    protected ProgressGaugeUI() {
       f = new Form("");
       gauge = new Gauge("", false, GAUGE_MAX, 0);
       stopCMD = new Command("Cancel", Command.STOP, 10);
       f.append(gauge);
       f.setCommandListener(this);
    }
 
    public static ProgressGaugeUI getInstance() {
       if (pgUI == null) {
           return new ProgressGaugeUI();
       }
       return pgUI;
    }
 
    public void reset() {
       current=0;
       gauge.setValue(0);
       stopped=false;
       setStoppable(false);
       setTitle("");
       setPrompt("");
    }
 
    public void updateProgress(Object param1) {//这里的参数设计为提示语
       current=(current+1);//%GAUGE_LEVELS;
       gauge.setValue(current );//* GAUGE_MAX/GAUGE_LEVELS);
       if(param1!=null && param1 instanceof String){
           setPrompt((String)param1);
       }
    }
 
    public boolean isStoppable() {
       return stoppable;
    }
 
    public void setStoppable(boolean stoppable) {
       this.stoppable = stoppable;
       if(stoppable){
           f.addCommand(stopCMD);
       }else{
           f.removeCommand(stopCMD);
       }
    }
 
    public boolean isStopped() {
       return stopped;
    }
 
public void setStopped(boolean stopped) {
       this.stopped=stopped;
    }
 
    public void setTitle(String title) {
       f.setTitle(title);
    }
 
    public void setPrompt(String prompt) {
       gauge.setLabel(prompt);
    }
 
    public void commandAction(Command arg0, Displayable arg1) {
       if(arg0==stopCMD){
           if(isStoppable())
              stopped=true;
           else{
              setPrompt("can't stop!");
           }
       }
    }
 
    public void show(Display display) {
       display.setCurrent(f);
    }
public void exit() {
       // 忽略
    }
    public void setMax() {
       gauge.setValue(GAUGE_MAX);
    }
}
